package com.main.tripplanner.clientservices;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.main.tripplanner.dao.AttractionDAO;
import com.main.tripplanner.dao.AttractionQuestionDAO;
import com.main.tripplanner.dao.CountryDAO;
import com.main.tripplanner.dao.RouteDAO;
import com.main.tripplanner.persistent.Attraction;
import com.main.tripplanner.persistent.AttractionQuestion;
import com.main.tripplanner.persistent.Country;
import com.main.tripplanner.persistent.Route;
import com.main.tripplanner.persistent.Vote;
import com.main.tripplanner.service.AttractionService;

@Service
public class QuestionClientService {
	@Autowired
	private AttractionService attractionService;
	@Autowired
	private CountryDAO countryDAO;
	@Autowired
	private AttractionDAO attractionDAO;
	@Autowired
	private AttractionQuestionDAO attractionQuestionDAO;
	@Autowired
	private RouteDAO routeDAO;
	
	private static QuestionClientService service = null;
	
	public static QuestionClientService getService() {
		if (service == null) {
			service = new QuestionClientService();
			return service;
		}
		return null;
	}

	public String getResponse(String countryId) {
		Country country = countryDAO.getCountryById(countryId);
		AttractionQuestion attractionQuestion = attractionService.getNextAttractionQuestion(country);
		return attractionQuestion.toJsonString(true);
	}

	public Attraction getResponse(Vote vote) {
		AttractionQuestion attractionQuestion = attractionQuestionDAO.getAttractionQuestionById(vote.getAttractionQuestionId());
		Attraction attraction = updateAttractionEnjoyment(vote);
		if(attraction.getEnjoymentLevel() > attractionQuestion.getCurrentAttraction().getEnjoymentLevel()){
			Route route = routeDAO.getRouteByCountry(attractionQuestion.getCountry());
			route.setToReplan(true);
			routeDAO.updateEntity(route);
		}
		attractionQuestionDAO.deleteEntity(attractionQuestion);
		return attraction;
	}

	private Attraction updateAttractionEnjoyment(Vote vote) {
		Attraction attraction = attractionDAO.getFullyInitializedAttractionById(vote.getAttraction().getId());
		float newEnjoymentLevel = 0L;
		if(attraction.getEnjoymentLevelVotes()==0){
			if(attraction.getEnjoymentLevel()==0){
				newEnjoymentLevel = vote.getVoteValue();
			}
			else{
				newEnjoymentLevel = (attraction.getEnjoymentLevel()+vote.getVoteValue())/2;
			}
		}
		else{
			newEnjoymentLevel = ((attraction.getEnjoymentLevel()*attraction.getEnjoymentLevelVotes()) + vote.getVoteValue()) / (attraction.getEnjoymentLevelVotes() +1);
		}
		attraction.setEnjoymentLevelVotes(attraction.getEnjoymentLevelVotes()+1);
		attraction.setEnjoymentLevel(newEnjoymentLevel);
		attractionDAO.updateEntity(attraction);
		return attraction;
	}
	
}
